from collections.abc import ItemsView
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from .models import StudyMaterial
from .utils.cos import upload_file


@require_http_methods(["GET"])
def get_resource_list(request):
    try:
        # 获取查询参数
        page = int(request.GET.get('page', 1))
        size = int(request.GET.get('size', 6))
        search = request.GET.get('search', '')
        material_type = request.GET.get('material_type', '')

        # 构建查询条件
        queryset = StudyMaterial.objects.all().order_by('-upload_time')  # 添加按上传时间降序排序

        if search:
            queryset = queryset.filter(
                Q(name__icontains=search) | 
                Q(description__icontains=search)
            )
            
        if material_type:
            queryset = queryset.filter(material_type__in=material_type.split(','))

        # 分页处理
        paginator = Paginator(queryset, size)
        page_obj = paginator.get_page(page)

        # 构建返回数据
        resources = []
        for item in page_obj.object_list:
            resources.append({
                'id': item.id,
                'name': item.name,
                'description': item.description,
                'file_size': item.file_size,  # 保持snake_case命名
                'download_count': item.download_count,
                'upload_time': item.upload_time.strftime('%Y-%m-%d %H:%M'),
                'material_type': item.get_material_type_display(),
                'download_url': item.file_path,
            })

        return JsonResponse({
            'code': 200,
            'message': 'success',
            'data': {
                'items': resources,
                'total': paginator.count,
                'page': page,
                'size': size
            }
        })

    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': str(e),
            'data': None
        })


@csrf_exempt
@require_http_methods(["POST"])
def upload_resource(request):
    try:
        if not request.FILES.get('file'):
            return JsonResponse({
                'code': 400,
                'message': '未上传文件',
                'data': None
            })

        file_obj = request.FILES['file']
        file_type = request.POST.get('material_type', 'notes')
        
        # 直接使用原文件名作为key
        file_key = f"resources/{file_type}/{file_obj.name}"
        
        # 调用COS上传方法
        file_url = upload_file(
            bucket='peeiep-1325738692',
            region='ap-shanghai',
            file_object=file_obj,
            key=file_key
        )

        # 创建数据库记录
        resource = StudyMaterial.objects.create(
            name=file_obj.name,
            description=request.POST.get('description', ''),
            file_size=file_obj.size,
            material_type=file_type,
            key=file_key,
            file_path=file_url
        )

        return JsonResponse({
            'code': 200,
            'message': '上传成功',
            'data': {
                'id': resource.id,
                'name': resource.name,
                'url': file_url,
                'file_size': resource.file_size,
                'material_type': resource.material_type
            }
        })

    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'上传失败: {str(e)}',
            'data': None
        })

